<template>
  <a-table
    :dataSource="userList"
    :columns="columns"
    :rowkey="rowkey"
    :loading="loading"
    :pagination="pagination"
    @change="handleTableChange"
  />
</template>

<script setup lang="ts">
import { ApiResponse, User } from "../../model/two/User";
import { useRequest } from "vue-request";
import { ref, computed, onMounted, watch } from "vue";
import axios from "../../api/request";

const current = ref(1);
const pageSize = ref(10);

const { data, loading, run } = useRequest<User[]>(
  () =>
    axios
      .get<ApiResponse>(
        `/api/userPage?page=${current.value}&pageSize=${pageSize.value}`
      )
      .then((res) => {
        userList.value = res.data.data;
        pagination.value.total = res.data.total;
        return res.data.data;
      }),
  {
    refreshDeps: [current, pageSize],
    manual: true,
  }
);

const userList = computed(() => data.value || []);

// 分页配置
const pagination = ref({
  current: current.value,
  pageSize: pageSize.value,
  total: 0,
  showTotal: (total: number) => `共 ${total} 条`,
  showSizeChanger: true,
  showQuickJumper: true,
  pageSizeOptions: ["5", "10", "20", "50"],
});

// 切换分页时触发
function handleTableChange(paginationChange: any) {
  current.value = paginationChange.current;
  pageSize.value = paginationChange.pageSize;
  pagination.value.current = paginationChange.current;
  pagination.value.pageSize = paginationChange.pageSize;
}

onMounted(() => {
  run(); // 页面初始加载
});

watch([current, pageSize], () => {
  run();
});

const columns = ref([
  { title: "编号", dataIndex: "id" },
  { title: "姓名", dataIndex: "name" },
  {
    title: "邮箱",
    dataIndex: "email",
    customRender: ({ text }) => {
      return text ?? "-"; // 显示 null 时渲染为 "-"
    },
  },
]);

function rowkey(r: User) {
  return r.id;
}
</script>